<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="./Js/jquery-3.5.1.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.5.0/axios.min.js"></script>
</head>
<body>
<script>
    var APPID="wx576478355cd34bb0";
    function getCode() { // 非静默授权，第一次有弹框
        const code = GetQueryString('code') // 截取路径中的code，如果没有就去微信授权，如果已经获取到了就直接传code给后台获取openId
        const local = window.location.href

        if (code == null || code === '') {
            window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + APPID + '&redirect_uri=' + encodeURIComponent(local) + '&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect'
        } else {
            getOpenId(code) //把code传给后台获取用户信息
        }
    }
    function getOpenId(code){
        axios.get('/wx/order?code='+code+"&amount=1").then(res=>{
            const data = res.data;
            if (typeof WeixinJSBridge == "undefined"){
                if( document.addEventListener ){
                    document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                }else if (document.attachEvent){
                    document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                    document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                }
            }else{
                onBridgeReady(data.timeStamp,data.nonceStr,data.prepayId,data.paySign);
            }
        })
    }
    function GetQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substring(1).match(reg);
        if(r != null) {
            return decodeURIComponent(r[2]);
        }
        return '';
    }
    getCode()
    function onBridgeReady(Timestamp,NonceStr,prepayId,paySign){
        WeixinJSBridge.invoke(
            'getBrandWCPayRequest', {
                "appId":APPID,     //公众号ID，由商户传入
                "timeStamp":Timestamp,    //时间戳，自1970年以来的秒数
                "nonceStr":NonceStr, //随机串
                "package":prepayId,
                "signType":"RSA",         //微信签名方式：
                "paySign":paySign //微信签名
            },
            function(res){
                if(res.err_msg == "get_brand_wcpay_request:ok" ){
                    // 使用以上方式判断前端返回,微信团队郑重提示：
                    alert("支付成功")
                    //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                }
            });
    }


</script>
</body>
</html>